package com.example.face2;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    private static final int IMAGE_REQUEST_CODE = 1000;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 1001;
    private String path;
    private ImageView showImage;
    private Button showFace;
    private Button chackFace;
    private static Gson gson;
    private String access_token = "";
    private static final int TOKEN = 100;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if(message.arg1==TOKEN){
                access_token = (String)message.obj;
                showFace("24.012fc86ec6e8038c5e3a41e505a00b68.2592000.1532343401.282335-11427684",
                        "application/json",
                        "027d8308a2ec665acb1bdf63e513bcb9",
                        "faceshape,facetype",
                        "FACE_TOKEN");
                Log.e("volley1",access_token);
            }
            return true;
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        onImageClick();
    }

    private void onImageClick() {
        showImage = findViewById(R.id.showImage);
        showFace = findViewById(R.id.showFace);
        chackFace = findViewById(R.id.chaceFace);
        showFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED)
                {
                    //权限还没有授予，需要在这里写申请权限的代码
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);
                }else {
                    //权限已经被授予，在这里直接写要执行的相应方法即可
                    Intent intent3 = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent3,IMAGE_REQUEST_CODE);
                }
            }
        });
        chackFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }

    private void init() {
        gson = new Gson();
        getToken("W2fzsGcIRGtYbnAVbcQlmqzs","AyHRvoeMPA0yVpzveEy4v45wtZFqLnNq");
    }

    private void getToken(String ik,String sk){
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+ik+"&client_secret="+sk+"&";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url,new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                // Log.e("volley",response.toString());
                Access_token access_token = gson.fromJson(response.toString(),Access_token.class);
                Message message = Message.obtain();
                message.obj = access_token.getAccess_token();
                message.arg1 = TOKEN;
                handler.sendMessage(message);
                Log.e("volley",access_token.getAccess_token());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        queue.add(jsonObjectRequest);
    }
    public void showFace(String at,String ct,String image,String ff,String it) {
        // 请求url
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=24.012fc86ec6e8038c5e3a41e505a00b68.2592000.1532343401.282335-11427684&" +
                "Content-Type=application/json&" +
                "image=027d8308a2ec665acb1bdf63e513bcb9&" +
                "face_field=faceshape,facetype&" +
                "image_type=FACE_TOKEN";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Canvas canvas = new Canvas();
                Paint p = new Paint();
                p.setColor(Color.RED);
                p.setStrokeWidth(10);
                canvas.drawRect(30,40,40,100,p);
                face face = gson.fromJson(response.toString(),face.class);
                Log.e("volley",response.toString());
                Log.e("volley",face.getResult().getFace_list().get(0).getLocation().getLeft()+","+
                        face.getResult().getFace_list().get(0).getLocation().getTop()+","+
                        face.getResult().getFace_list().get(0).getLocation().getWidth()+","+
                        face.getResult().getFace_list().get(0).getLocation().getHeight());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(jsonObjectRequest);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2){
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Intent intent3 = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent3,IMAGE_REQUEST_CODE);
            }else{
                Toast.makeText(MainActivity.this, "你还未同意使用相册权限！", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode){
            //图片
            case IMAGE_REQUEST_CODE:
                if(resultCode == Activity.RESULT_OK && data != null){
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    path = cursor.getString(columnIndex);  //获取照片路径
                    cursor.close();
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    showImage.setImageBitmap(bitmap);
                    Log.e("AddActivity",path);
                }
                break;
        }
    }
}
